package com.vehicle.repair.controller;

import com.vehicle.repair.model.PaymentRecord;
import com.vehicle.repair.service.PaymentService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/payments")
public class PaymentController {
    private final PaymentService paymentService;

    public PaymentController(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @PostMapping
    public ResponseEntity<PaymentRecord> createPaymentRecord(@RequestParam Integer orderId) {
        try {
            PaymentRecord record = paymentService.createPaymentRecord(orderId);
            return ResponseEntity.ok(record);
        } catch (IllegalArgumentException | IllegalStateException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<PaymentRecord> getPaymentRecordById(@PathVariable Integer id) {
        Optional<PaymentRecord> record = paymentService.getPaymentRecordById(id);
        return record.map(ResponseEntity::ok)
                   .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping("/order/{orderId}")
    public ResponseEntity<PaymentRecord> getPaymentRecordByOrder(@PathVariable Integer orderId) {
        try {
            Optional<PaymentRecord> record = paymentService.getPaymentRecordByOrder(orderId);
            return record.map(ResponseEntity::ok)
                       .orElseGet(() -> ResponseEntity.notFound().build());
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/repairer/{repairerId}")
    public ResponseEntity<List<PaymentRecord>> getPaymentRecordsByRepairer(@PathVariable Integer repairerId) {
        try {
            List<PaymentRecord> records = paymentService.getPaymentRecordsByRepairer(repairerId);
            return ResponseEntity.ok(records);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/repairer/{repairerId}/total-income")
    public ResponseEntity<Double> getTotalIncomeForRepairer(@PathVariable Integer repairerId) {
        try {
            double totalIncome = paymentService.getTotalIncomeForRepairer(repairerId);
            return ResponseEntity.ok(totalIncome);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }
}
